<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 赛程管理</el-breadcrumb-item>
                <el-breadcrumb-item>赛程</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-card>
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column label="比赛名称" prop="cname" align="center"/>
                <el-table-column label="比赛预估耗时" prop="timeNeed" align="center"/>
                <el-table-column label="比赛规则" prop="crule" align="center"/>
                <el-table-column align="center">
                <template #header>
                    <el-input v-model="search" size="small" placeholder="请输入选手编号" clearable>
                        <template #append>
                            <el-button @click="handleSearch()" icon="el-icon-search">
                                查询
                            </el-button>
                        </template>
                    </el-input>
                </template>
                <template #default="scope">
                    <!-- <el-button size="small" @click="handleEdit(scope.$index, scope.row)" type="danger">改变裁判</el-button> -->
                    <el-button size="small" @click="showScore(scope.$index,scope.row)" type="primary">展示成绩</el-button>
                </template>
                </el-table-column>
            </el-table>
        </el-card>
        
        <!-- 编辑弹出框 -->
        <el-dialog v-model="dialogFormVisible" title="个人成绩" center>
            <el-card shadow="hover">
                <el-table :data="ownScoreTable" border style="width: 100%">
                    <el-table-column label="比赛名称" prop="cname" align="center"/>
                    <el-table-column label="选手编号" prop="pid" align="center"/>
                    <el-table-column label="选手姓名" prop="name" align="center"/>
                    <el-table-column label="所属学校" prop="school" align="center"/>
                    <el-table-column label="成绩" prop="score" align="center"/>
                </el-table>
            </el-card>
        </el-dialog>
            
        <!-- 图表 -->
        <div id="scoreCharts" class="div-echarts" v-show="showEcharts"></div>
        <!-- 分页 -->
        <el-card>
            <el-pagination v-model:currentPage="currentPage" v-model:page-size="pageSize"
                background="true"
                layout="total, prev, pager, next, jumper"
                :total="parseInt(totalNum)" 
                :page-sizes="pageSize"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>
    </div>
  
</template>

<script>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from 'vuex';
import { map } from "lodash";

//Echarts begin
import * as echarts from 'echarts/core';
import {
    DatasetComponent,
    GridComponent,
    TransformComponent,
    TooltipComponent,
} from 'echarts/components';
import { BarChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([
    DatasetComponent,
    GridComponent,
    TransformComponent,
    TooltipComponent,
    BarChart,
    CanvasRenderer
]);
var myChart;
//echarts end

export default{
    setup(){
        const store  = useStore();

        let dialogFormVisible = ref(false)
        const formLabelWidth = '140px'
        

        //表格数据
        let tableData = reactive([]);
        const getCompetitionList = ()=>{
            store.dispatch("AllPlayerScoreByCompetition",{
                page:currentPage.value,
                pageSize:pageSize.value,
            })
            .then((res)=>{
                if(res.code===200){
                    totalNum.value = res.obj.records;
                    // console.log("#通过比赛获取成绩结果",res)
                    tableData.splice(0,tableData.length,...map(res.obj.rows,item=>{
                        return {
                            cname: item.cname,
                            timeNeed:item.timeNeed,
                            crule:item.crule,
                            players:map(item.player1s,each=>{
                                return [
                                    each.name,
                                    each.score,
                                ]
                            })
                        }
                    }))
                    // console.log("@通过比赛获取成绩列表-tableData ",tableData);
                }
            })
            .catch(err=>{
                console.log("报错为",err)
            })
        }

        //选手个人成绩表
        let ownScoreTable = reactive([
            {
                cname:"1",
                name:"2",
                pid:"3",
                school:"4",
                score:"5"
            }
        ]);
        //搜索 begin
        const search = ref('');
        const handleSearch = ()=>{
            // console.log("搜索内容",search)
            if(search.value.length<1)
                return ;
            store.dispatch("GetOwnScores",search.value)
            .then((res)=>{
                if(res.code===200){
                    // console.log("@查询结果为",res.obj[0]);
                    dialogFormVisible.value=true;
                    let tep = res
                    ownScoreTable.splice(0,ownScoreTable.length,...flatCompetitions(res.obj));
                    // console.log("###结果为",ownScoreTable)
                }else{
                    ElMessage({
                        type:"error",
                        message:res.message,
                        center:true,
                    })
                }
            })
            .catch(err=>{
                console.log("报错为",err)
            })
        }
        //搜索 end

        //处理嵌套数组
        function flatCompetitions(x) {
            let ret = [];
            for (let person of x) {
                let competitions = person.competitions;
                delete person.competitions;
                for (let cpt of competitions) {
                    Object.assign(cpt, person);
                    ret.push(cpt);
                }
            }
            // console.log(ret);
            return ret;  
        }


        //echarts
        let showEcharts = ref(false);
        let curScoreIndex = ref(-1);
        function showScore(index,row){
            if(curScoreIndex.value!=index||curScoreIndex.value===-1){
                curScoreIndex.value = index;
                showEcharts.value = true;
            }else{
                console
                showEcharts.value = !showEcharts.value;
            }
            // console.log("是否相等",curScoreIndex.value===-1)
            console.log("展示成绩",row.players);
            var option;

            option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                
                dataset: [
                    {
                        dimensions: ['name', 'score'],
                        source: reactive(row.players)
                    },
                    {
                        transform: {
                            type: 'sort',
                            config: { dimension: 'score', order: 'desc' }
                        }
                    }
                ],
                xAxis: {
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                },
                yAxis: {
                    name:'分数',
                    nameLocation:'end'
                },
                series: {
                    type: 'bar',
                    encode: { x: 'name', y: 'score' },
                    datasetIndex: 1
                }
            };

            option && myChart.setOption(option);
        }
        

        onMounted(()=>{
            //设置 setOption 时，必须要在 dom 加载完之后加载。
            myChart = echarts.init(document.getElementById('scoreCharts'));

            getCompetitionList();

        })
        
        //分页
        let currentPage = ref(1);
        let pageSize = ref(7);
        let totalNum = ref(14);//总条数除以每页显示条数5
        const handleSizeChange = (val) => {
            console.log(`${val} items per page`)
        }
        const handleCurrentChange = (val) => {
            console.log(`current page: ${val}`)
            getCompetitionList();
        }

        return {
            dialogFormVisible,
            formLabelWidth,
            ownScoreTable,

            handleSearch,
            search,

            tableData,
            getCompetitionList,

            showEcharts,
            showScore,

           
            //分页
            currentPage,
            pageSize,
            totalNum,
            handleSizeChange,
            handleCurrentChange,
        }
    }
}
</script>

<style scoped>
    .div-echarts{
        width: 600px;
        height:400px;
        /* 居中显示 */
        margin: 0 auto;        
    }
</style>